/*
 * Description: process preload entrance
 */
#include "process_preload_entrance.h"
#include <algorithm>
#include <memory>
#include "performance/utils/perf_utils.h"
#include "log.h"

namespace PERF {

ProcessPreloadEntrance::ProcessPreloadEntrance()
{
    pnameToApp = {};
    appToPreloader = {};
}

std::shared_ptr<ProcessPreloader> ProcessPreloadEntrance::GetPreloader(PreloadApp app)
{
    if (appToPreloader.find(app) == appToPreloader.end()) {
        return nullptr;
    }
    std::shared_ptr<ProcessPreloader> &pPreloader = appToPreloader[app];
    return pPreloader;
}

PreloadApp ProcessPreloadEntrance::GetAppEnumByPname(const std::string &pname)
{
    if (pnameToApp.find(pname) == pnameToApp.end()) {
        return PreloadApp::UNKNOWN;
    }
    PreloadApp app = pnameToApp[pname];
    return app;
}

void ProcessPreloadEntrance::DoPreload(const std::string &pname)
{
    if (PERF_UTILS.IsProcessExists(pname)) {
        return;
    }
    PreloadApp app = GetAppEnumByPname(pname);
    if (appToPreloader.find(app) == appToPreloader.end()) {
        return;
    }
    auto pPreloader = GetPreloader(app);
    if (pPreloader != nullptr) {
        pPreloader->DoPreload();
    }
}

void ProcessPreloadEntrance::DoAwaken(std::shared_ptr<PerfInfo> perfInfo)
{
    if (perfInfo == nullptr) {
        return;
    }
    LOG_INFO("[PERF - DoAwaken] - appName: {}, filepath: {}", perfInfo->appName, perfInfo->filepath);
    PreloadApp app = GetAppEnumByPname(perfInfo->appName);
    if (appToPreloader.find(app) == appToPreloader.end()) {
        return;
    }
    auto pPreloader = GetPreloader(app);
    if (pPreloader != nullptr) {
        pPreloader->DoAwaken(perfInfo->filepath);
    }
}

void ProcessPreloadEntrance::Resume(const std::string &pname)
{
    PreloadApp app = GetAppEnumByPname(pname);
    if (appToPreloader.find(app) == appToPreloader.end()) {
        return;
    }
    auto pPreloader = GetPreloader(app);
    if (pPreloader != nullptr) {
        pPreloader->Resume();
    }
}
}  // namespace PERF